package com.fisco.bcos.asset.client;

import com.fisco.bcos.asset.contract.Asset;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.fisco.bcos.sdk.model.callback.TransactionCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

@Component
public class AssetClient {
    @Autowired
    private BcosSDK bcosSDK;
    @Autowired
    private Client client;
    @Autowired
    private CryptoKeyPair cryptoKeyPair;
    @Value("${fisco.contractAddress.asset}")
    private String contractAddress;

    /**
     * 发布资产（条件：当前用户是Asset合约发布者）
     * @param receiver 接收者地址
     * @param amount 资产数量
     */
    public void issueAsset(String receiver, BigInteger amount) {
        Asset asset = Asset.load(contractAddress, client, cryptoKeyPair);
        asset.issue(receiver, amount, new CallbackResponse());
    }

    /**
     * 发送资产（条件：发送者的账号Balance必须大于等于amount）
     * @param receiver 接收者地址
     * @param amount 资产数量
     */
    public void sendAsset(String receiver, BigInteger amount) {
        Asset asset = Asset.load(contractAddress, client, cryptoKeyPair);
        asset.send(receiver, amount, new CallbackResponse());
    }

    private class CallbackResponse extends TransactionCallback {

        @Override
        public void onResponse(TransactionReceipt transactionReceipt) {
            System.out.println("回调结果：");
            System.out.println(transactionReceipt.getContractAddress());
            System.out.println(transactionReceipt.getFrom());
            System.out.println(transactionReceipt.getGasUsed());
            System.out.println(transactionReceipt.getRemainGas());
            System.out.println(transactionReceipt.getStatus());
            System.out.println(transactionReceipt.getMessage());
            System.out.println(transactionReceipt.getStatusMsg());
        }
    }
}
